【例子介绍】
【相关图片】
【源码结构】
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo;
btnWrite: TButton;
btnRead: TButton;
btnAppend: TButton;
Edit1: TEdit;
Edit2: TEdit;
procedure FormShow(Sender: TObject);
procedure btnWriteClick(Sender: TObject);
procedure btnReadClick(Sender: TObject);
procedure btnAppendClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
sFileName: string;
implementation
{$R *.dfm}
//把Edit2.text 写入到文件中
procedure TForm1.btnAppendClick(Sender: TObject);
var f: TextFile;
i: integer;
s: string;
t: TTime;
begin
AssignFile(f,sFileName);
if not FileExists(sFileName) then
begin
ShowMessage('文件不存在。');
exit;
end;
Append(f);
for i := 0 to 999 do
begin
s:=TimeToStr(Now);
WriteLn(f,s);
end;
CloseFile(f);
end;
procedure TForm1.btnReadClick(Sender: TObject);
var f: TextFile;
s: string;
ss: TStringList;
begin
AssignFile(f,sFileName);
ss:=TStringList.Create;
if not FileExists(sFileName) then
begin
ShowMessage('文件不存在。');
exit;
end;
//if file really exists,
Reset(f); // Open this file, for Read Only
while not Eof(f) do
begin
ReadLn(f,s);
ss.Add(s);
//Memo1.Lines.Add(s); // 慢
end;
CloseFile(f);
Memo1.Lines:=ss;
ss.Free;
end;
procedure TForm1.btnWriteClick(Sender: TObject);
var f: TextFile;
begin
AssignFile(f,sFileName);
if FileExists(sFileName) then
begin
Append(f);//打开已经存在的文件,并移动文件指针到文件尾
end else begin
ReWrite(f);//创建并打开
end;
WriteLn(f,Edit2.Text);
CloseFile(f);
end;
procedure TForm1.FormShow(Sender: TObject);
begin
sFileName:=ExtractFilePath(Application.ExeName) '123.txt';
Caption:='Application.ExeName=' Application.ExeName;
Edit1.Text:='sFileName: ' sFileName;
end;
end.
评论